<template>
  <div class="artile-list" ref="listRef">
    <van-pull-refresh v-model="refreshing" :success-text="refreshTip" :success-duration="2000" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <!-- <van-cell
          :v-for="(item, index) in list"
          :key="index"
          :title="item.title"
        /> -->
        <article-item v-for="(item, index) in list"
          :key="index" :article="item"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import ArticleItem from '@/components/article-item.vue'
export default {
  name: 'ArticleList',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false, // 加载中
      finished: false, // 是否结束
      error: false, // 是否错误
      timestamp: Date.now(),
      refreshing: false, // 是否下拉刷新中
      refreshTip: ''
    }
  },
  components: { ArticleItem },
  activated () {
    console.log('activated')
    // 回来
    this.$refs.listRef.scrollTop = localStorage.scrollTop || 0
  },
  deactivated () {
    console.log('deactivated')
    // 离开
  },
  created () {},
  mounted () {
    this.$refs.listRef.onscroll = function () {
      localStorage.scrollTop = this.scrollTop
    }
  },
  methods: {
    // 页面打开&触底执行
    async onLoad () {
      try {
      // 1发送请求
        const { data: { data: { results, pre_timestamp: timestamp } } } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp
        })
        // 模拟错误
        // if (Math.random() > 0.5) {
        //   JSON.parse('{username: "zs"}')
        // }
        // 2.追加数据
        this.list.push(...results)
        // 更新时间戳
        this.timestamp = timestamp

        // 3.加载状态结束
        this.loading = false

        // this.finished = true

        // 4.判断数据全部加载完成
        if (timestamp == null || results.length === 0) {
          this.finished = true
        }
      } catch (e) {
        this.loading = false
        this.error = true
      }
    },
    async onRefresh () {
      try {
        // 1.发请求
        const { data: { data: { results } } } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        // 模拟错误
        JSON.parse('{username: "zs"}')
        // 2.放置数据
        this.list.unshift(...results)
        // 3.关闭状态值
        this.refreshing = false
        this.refreshTip = '获取数据成功'
      } catch (error) {
        this.refreshing = false
        this.refreshTip = '获取数据失败,请稍后重试'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.artile-list{
  height: 79vh;
  overflow-y: auto;
}
</style>
